package com.zx.template.controller.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user")
public class WxMaUserController {
    private final WxMaService wxMaService;



    private String getWxPhone(WxLoginUserDto dto){
        Assert.isTrue(StrUtil.isNotBlank(dto.getEncryptedData()),"encryptedData 不能为空");
        Assert.isTrue(StrUtil.isNotBlank(dto.getIv()),"iv 不能为空");
        Assert.isTrue(StrUtil.isNotBlank(dto.getSessionKey()),"sessionKey 为空");
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(dto.getSessionKey(), dto.getEncryptedData(), dto.getIv());
        return  phoneNoInfo.getPhoneNumber();
    }
  
    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public String login(@RequestBody WxLoginUserDto dto) throws WxErrorException {
  
        
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(dto.getCode());
        log.info(session.getSessionKey());
        log.info(session.getOpenid());
        //TODO 可以增加自己的逻辑，关联业务相关数据
        return JSONUtil.toJsonStr(session);
        
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JSONUtil.toJsonStr(userInfo);
    }

   

}
